package ghelp

import (
	"log"
	"math/rand"
	"reflect"
	"strconv"
	"time"
)

// GetRandomString 获取随机字符串包含数字26位字母(循环调用会重复)
func GetRandomString(l int) string {
	str := "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < l; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}

// GetRandomInt 获取随机数字(循环调用会重复)
func GetRandomInt(l int) string {
	str := "0123456789"
	bytes := []byte(str)
	result := []byte{}
	r := rand.New(rand.NewSource(time.Now().UnixNano()))
	for i := 0; i < l; i++ {
		result = append(result, bytes[r.Intn(len(bytes))])
	}
	return string(result)
}

// Go 封装go
// 解决go panic后导致整个进程挂了
// example: Go(ConvertWordToImage, "/1.docx", "2.jpg")
func Go(callback interface{}, args ...interface{}) {
	v := reflect.ValueOf(callback)
	if v.Kind() != reflect.Func {
		panic("not a function")
	}
	vargs := make([]reflect.Value, len(args))
	for i, arg := range args {
		vargs[i] = reflect.ValueOf(arg)
	}
	go func() {
		defer func() {
			if err := recover(); err != nil {
				log.Println("Go err:", err)
			}
		}()
		v.Call(vargs)
	}()
}

// JwdToDfm 经纬度字符值转化成度、分、秒
func JwdToDfm(d string) (int, int, int) {
	var D, F, M int
	f, err := strconv.ParseFloat(d, 10)
	if err != nil {
		return D, F, M
	}
	D = int(f)
	_f := (f - float64(D)) * 60
	F = int(_f)
	_m := (_f - float64(F)) * 60
	M = int(_m)
	return D, F, M
}

func KeyExists(key interface{}, m map[interface{}]interface{}) bool {
	_, ok := m[key]
	return ok
}
